import { NOT_LOADED, LOADING_SOURCE_CODE, NOT_BOOTSTRAPPED, BOOTSTRAPPING, NOT_MOUNTED, MOUNTED, SKIP_BECAUSE_BROKEN, shouldBeActive } from './app.helpers';
import { reroute } from '../navigation/reroute.js';

// 保存注册的应用
const apps = [];

/**
 * 
 * @param {*} appName 应用名称
 * @param {*} loadApp 加载的应用
 * @param {*} activeWhen 激活是会调用loadApp
 * @param {*} customProps 自定义属性
 */
export function registerApplication(appName, loadApp, activeWhen, customProps) {
    apps.push({
        name: appName,
        loadApp,
        activeWhen,
        customProps,
        status: NOT_LOADED // 默认应用为未加载
    });

    reroute(); // 加载应用
}

// 筛选不同状态的应用
export function getAppChanges() {
    const appsToLoad = [];
    const appsToMount = [];
    const appsToUnmount = [];
    apps.forEach(app => {
        // 没有出错，并且应该被加载 activeWhen和url匹配
        const appShouldBeActive = app.status !== SKIP_BECAUSE_BROKEN && shouldBeActive(app);
        switch (app.status) { // toLoad
            case NOT_LOADED:
            case LOADING_SOURCE_CODE:
                if (appShouldBeActive) {
                    appsToLoad.push(app);
                }
                break;
            case NOT_BOOTSTRAPPED: // toMount
            case BOOTSTRAPPING:
            case NOT_MOUNTED:
                if (appShouldBeActive) {
                    appsToMount.push(app);
                }
                break
            case MOUNTED: // toUnmount
                if (!appShouldBeActive) {
                    appsToUnmount.push(app);
                }
        }
    });
    return { appsToUnmount, appsToLoad, appsToMount }
}